const { exec } = require('../db/mysql');

/**
 * 获取博客列表
 * @param author 作者
 * @param keyword 关键词
 * @returns {SuccessModel|*}
 */
const getBlogList = (author, keyword) => {
    let sql = `select * from blogs where 1=1`;
    author && (sql += ` and author='${author}'`);
    keyword && (sql += ` and title like '%${keyword}%'`);
    sql += ` order by createtime desc;`;

    return exec(sql);
};

/**
 *
 * 获取博客详情
 * @param id 博客 Id
 */
const getBlogDetail = (id) => {
    const sql = `select * from blogs where id='${id}';`;
    return exec(sql).then(rows => rows[0]);
};

/**
 * 新建博客
 */
const createBlog = (blogData = {}) => {
    const { author, title, content, createtime = Date.now() } = blogData;
    const sql = `
        insert into blogs (author, title, content, createtime) 
        values ('${author}', '${title}', '${content}', ${createtime});
    `;
    return exec(sql).then(({ insertId }) => ({id: insertId}));
};

const updateBlog = (id, blogData = {}) => {
    const { title, content, createtime = Date.now() } = blogData;
    const sql = `
        update blogs set title='${title}', content='${content}', createtime=${createtime}
        where id=${id};
    `;
    return exec(sql).then(({ affectedRows }) => affectedRows > 0);
};

/**
 * 删除博客
 * @param id
 */
const deleteBlog = (id, author) => {
    const sql = `
        delete from blogs where id=${id} and author='${author}';
    `;
    return exec(sql).then(({ affectedRows }) => affectedRows > 0);
};

module.exports = {
    getBlogList,
    getBlogDetail,
    createBlog,
    updateBlog,
    deleteBlog,
};
